﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.IO;
using System.Configuration;

using ScanSnap.Domain;
using ScanSnap.Util;
using ScanSnap.Domain.JSON;
using System.Collections.Specialized;

namespace ScanSnap
{
    /// <summary>
    /// Interaction logic for ModelWindow.xaml
    /// </summary>
    public partial class ModelWindow : Window
    {
        public List<Document> documentNameList { get; set; }
        public List<Tag> TagList { get; set; }
        public List<Tag> CustomTagList { get; set; }
        public int DefaultIndex { get; set; }
        public List<Organization> Organizations { get; set; }
        public ObservableCollection<FileEntry> PdfFileList { get; set; }
        public int NumberOfFiles { get; set; }
        public List<Patient> PatientList { get; set; }
        public List<DocumentType> DocumentTypeList { get; set; }

        public readonly string INVALID_ID = "選択してください";
        System.Windows.Threading.DispatcherTimer dispatcherTimer;

        private readonly string SERVER_URL = ConfigurationManager.AppSettings["url"];

        public List<string> ErrorList { set; get; }

        private Organization org = new Organization();
        private User user;


        enum PERIOD { YEAR, MONTH, WEEK, DATE };

        public ModelWindow(User user)
        {
            InitializeComponent();
            this.user = user;
            SetProfile();
            LoadOrganizations();
            LoadDocumentType();

            NumberOfFiles = 0;
            LoadPdfFileList();
            //PdfGrabTimer();
            
            /*
            databaseConnection = new Database(userType);

            TagList = new ObservableCollection<BoolStringClass>();
            
            ComboDocumentType.SelectedIndex = 0;
            DefaultIndex = 0;
            ComboRetentionPeriodSearchValue.SelectedIndex = 0;

            TagSet = databaseConnection.FindByTagGroup(0);

            this.DataContext = this;
            Organizations = new ObservableCollection<Organization>();

            this.org = databaseConnection.FindByOrganizationId(databaseConnection.OrganizationList[0].Id);

            NumberOfFiles = 0;
            LoadPdfFileList();
            PdfGrabTimer();
            */
            //SearchPatientComponentView(System.Windows.Visibility.Hidden);
        }

        private void SetProfile()
        {
            FirstNameText.Content = this.user.FirstName;
            LastNameText.Content = this.user.LastName;
        }

        private void LoadOrganizations()
        {
            string userId = user.Id;

            NameValueCollection vals = new NameValueCollection();
            vals.Add("anyId", userId);

            OrganizationJSON orgs = JsonReader.JsonDeserialize<OrganizationJSON>(SERVER_URL + "/search/search-organizations-by-user-json", "POST", vals);

            if (orgs != null)
            {
                if (orgs.Organizations != null)
                {
                    this.Organizations = orgs.Organizations;
                    ComboOrganizationName.ItemsSource = Organizations;
                }
            }
        }

        public void LoadPatients()
        {

        }

        public void LoadDocumentType()
        {
            DocumentTypeJSON dtj = JsonReader.JsonDeserialize<DocumentTypeJSON>(SERVER_URL + "/search/search-document-types-json", "POST");
            if (dtj != null)
            {
                DocumentTypeList = dtj.DocumentTypes;
                ComboDocumentType.ItemsSource = DocumentTypeList;
            }
            
        }

        public void LoadDocumentNames(String documentTypeId)
        {
            NameValueCollection vals = new NameValueCollection();
            vals.Add("anyId", documentTypeId);
            string resourceUrl = "/search/search-document-json.html";
            DocumentNameJSON dnj = JsonReader.JsonDeserialize<DocumentNameJSON>(SERVER_URL + resourceUrl, "POST", vals);
            if (dnj != null)
            {
                documentNameList = dnj.Documents;
                ComboDocumentName.ItemsSource = documentNameList;
            }

        }

        public void LoadTags(String documentNameId)
        {
            NameValueCollection vals = new NameValueCollection();
            vals.Add("anyId", documentNameId);

            string resourceUrl = "/search/search-document-tags-json.html";
            TagJSON tj = JsonReader.JsonDeserialize<TagJSON>(SERVER_URL + resourceUrl, "POST", vals);
            if (tj != null)
            {
                TagList = tj.DocumentTags;
                CustomTagList = tj.CustomTags;
                ListViewDocumentTag.ItemsSource = TagList;
                ListViewDocumentCustomTag.ItemsSource = CustomTagList;
            }

        }

        private void PdfGrabTimer()
        {
            dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
            dispatcherTimer.Start();
            dispatcherTimer.IsEnabled = true;
        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            LoadPdfFileList();
        }

        private void LoadPdfFileList()
        {
            
            string pdfPath = ConfigurationManager.AppSettings["scansnap_folder"];

            DirectoryInfo info = new DirectoryInfo(@pdfPath);

            if (!Directory.Exists(@pdfPath))
            {
                ErrorList = new List<string>();
                ErrorList.Add("Scansnap folder configuration error" + Environment.NewLine + 
                    "please configure Scansnap.exe.config file" + Environment.NewLine + 
                    @pdfPath + " folder may not exist");
                if (dispatcherTimer != null && dispatcherTimer.IsEnabled)
                {
                    dispatcherTimer.Stop();
                    dispatcherTimer.IsEnabled = false;
                }
                new ErrorWindow(ErrorList).Show();
                return;
            }

            List<FileInfo> list = info.GetFiles("*.pdf").OrderByDescending(p => p.CreationTime).ToList();

            if (PdfFileList == null)
                PdfFileList = new ObservableCollection<FileEntry>();
            //else
              //  PdfFileList.Clear();
            FileEntry fe;
            foreach(FileInfo f in list) {
                fe = new FileEntry { Name = f.Name, FullName = f.FullName, DateCreated = f.CreationTime.ToString(), IsSelected = false, ReadOnly = f.IsReadOnly };
               
                if(PdfFileList.Contains(fe) == false)
                    PdfFileList.Add(fe);
            }

            ListViewFile.ItemsSource = PdfFileList;
        }

        private void OnDragMoveWindow(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void OnMinimizeWindow(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void OnMaximizeWindow(object sender, MouseButtonEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
                this.WindowState = WindowState.Normal;
            else if (this.WindowState == WindowState.Normal)
                this.WindowState = WindowState.Maximized;
        }

        private void OnCloseWindow(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void TreeViewPatientMouseClickUp(object sender, MouseButtonEventArgs e)
        {
            TextBlock documentName = (TextBlock)sender;
            string fullPath = documentName.ToolTip.ToString();
            string pdfPath = ConfigurationManager.AppSettings["patient_documents"];
            BrowserPdfViewer.Source = new Uri(new System.IO.FileInfo(fullPath).FullName);//new Uri(new System.IO.FileInfo(@pdfPath + "\\" + documentName.Text).FullName);
        }

        private void TreeViewOrgatizationMouseClickUp(object sender, MouseButtonEventArgs e)
        {
            TextBlock documentName = (TextBlock)sender;
            string fullPath = documentName.ToolTip.ToString();
            
            string pdfPath = ConfigurationManager.AppSettings["organization_documents"];
            BrowserPdfViewer.Source = new Uri(new System.IO.FileInfo(fullPath).FullName);//new Uri(new System.IO.FileInfo(@pdfPath + "\\" + documentName.Text).FullName);
        }

        /**  FormButtons **/
        private void ButtonFormSubmit_Click(object sender, RoutedEventArgs e)
        {
            ValidateButtonFormSubmit();

            if (ErrorList.Count != 0)
            {
                new ErrorWindow(ErrorList).Show();
                return;
            }

            string organizationId = TextOrganizationId.Text;
            string organizationName = ComboOrganizationName.SelectedValue.ToString();

            string documentType = ComboDocumentType.SelectedValue.ToString();
            string documentName = ComboDocumentName.SelectedValue.ToString();


            string patientPath = ConfigurationManager.AppSettings["patient_documents"];
            string organizationPath = ConfigurationManager.AppSettings["organization_documents"];
            string pdfPath = ConfigurationManager.AppSettings["scansnap_folder"];

            string selectedPath = "";
            string selectedFileName = "";
            foreach(FileEntry f in PdfFileList) {
                if (f.IsSelected == true)
                {
                    selectedPath = f.FullName;
                    selectedFileName = f.Name;
                    break;
                }
            }

            if(ComboDocumentType.SelectedIndex == 2)
            {
                if (!Directory.Exists(@patientPath + "\\" + documentName))
                {
                    Directory.CreateDirectory(@patientPath + "\\" + documentName);
                }

                try
                {
                    dispatcherTimer.IsEnabled = false;
                    dispatcherTimer.Stop(); //to prevent file attribute settings
                    
                    File.Copy(selectedPath, @patientPath + "\\" + documentName + "\\" + selectedFileName, true);
                    //File.Delete(selectedPath);
                }catch //(IOException ex)
                {
                    ErrorList = new List<string>();
                    ErrorList.Add("ファイルは既にアップロードされました");
                    new ErrorWindow(ErrorList).Show();
                    return;
                } finally{
                    if (dispatcherTimer.IsEnabled == false)
                    {
                        dispatcherTimer.IsEnabled = true;
                        dispatcherTimer.Start();
                    }
                }


            } else if(ComboDocumentType.SelectedIndex == 1 || ComboDocumentType.SelectedIndex == 3)
            {
                if (!Directory.Exists(organizationPath + "\\" + documentName))
                {
                    Directory.CreateDirectory(organizationPath + "\\" + documentName);
                }

                try
                {
                    dispatcherTimer.IsEnabled = false;
                    dispatcherTimer.Stop(); //to prevent file attribute settings
                    //File.Move(selectedPath, organizationPath + "\\" + documentName + "\\" + selectedFileName);
                    File.Copy(selectedPath, organizationPath + "\\" + documentName + "\\" + selectedFileName, true);
                    //File.Delete(selectedPath);
                }
                catch //(IOException ex)
                {
                    ErrorList = new List<string>();
                    ErrorList.Add("ファイルは既にアップロードされました");
                    new ErrorWindow(ErrorList).Show();
                    return;
                }
                finally
                {
                    if (dispatcherTimer.IsEnabled == false)
                    {
                        dispatcherTimer.IsEnabled = true;
                        dispatcherTimer.Start();
                    }
                }
                
            }

            new ConfirmationWindow().Show();

            if (RadioCacheNo.IsChecked == true)
            {
                resetUploadForm();
            }
        }

        private void ValidateButtonFormSubmit()
        {
            ErrorList = new List<string>();

            if (ComboOrganizationName.SelectedIndex == 0)
            {
                ErrorList.Add("事業所IDを入力してください");
                ErrorList.Add("事業所名を選択してください");
            }

            if (ComboDocumentType.SelectedIndex == 0)
                ErrorList.Add("事業所IDを入力してください");

            if (ComboDocumentName.SelectedIndex == 0)
                ErrorList.Add("事業所IDを入力してください");

            if(RadioAttachmentNo.IsChecked == false && RadioAttachmentYes.IsChecked == false)
                ErrorList.Add("添付書類の有無を選択してください");

            if (RadioPdfDateNo.IsChecked == false && RadioPdfDateYes.IsChecked == false)
                ErrorList.Add("保存期間の指定の有無を選択してください");

            if (RadioRetentionPeriodNo.IsChecked == false && RadioRetentionPeriodYes.IsChecked == false)
                ErrorList.Add("書類の日付の有無を選択してください");

            bool hasSelected = false;
            foreach(FileEntry f in PdfFileList) {
                if (f.IsSelected == true)
                {
                    hasSelected = true;
                    break;
                }
            }

            if (hasSelected == false)
                ErrorList.Add("書類情報を選択してください");
            

        }

        private void ButtonFormClear_Click(object sender, RoutedEventArgs e)
        {
            resetUploadForm();
        }

        private void resetUploadForm()
        {
            TextPatientId.Text = "";
            ComboPatientName.SelectedIndex = 0;
            LabelPatientAddress.Content = "";
            LabelPatientDateOfBirth.Content = "";
            LabelPatientSex.Content = "";
            ComboDocumentType.SelectedIndex = 0;
            ComboDocumentName.SelectedIndex = 0;
            ComboOrganizationName.SelectedIndex = 0;
            RadioPdfDateYes.IsChecked = false;
            RadioPdfDateNo.IsChecked = false;
            RadioRetentionPeriodYes.IsChecked = false;
            RadioRetentionPeriodNo.IsChecked = false;
            DatePickerPdfDate.Text = "";
            ComboRetentionPeriodUnit.SelectedValue = "";
            ComboRetentionPeriodValue.SelectedValue = "";

            foreach (FileEntry f in PdfFileList)
            {
                if (f.IsSelected == true)
                {
                    f.IsSelected = false;
                }
            }
        }

        private void ButtonFormFinish_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /**  SearchButtons **/
        private void ButtonSearchSubmit_Click(object sender, RoutedEventArgs e)
        {
            SubmitValidation();

            if (ErrorList.Count != 0)
            {
                new ErrorWindow(ErrorList).Show();
                return;
            }
                
            string organizationId = TextOrganizationSearchId.Text;

            
            
            Organizations.Add(org);
            TreeViewDocumentTypeAC.DataContext = Organizations;
            TreeViewDocumentTypeB.DataContext = Organizations;

        }


        private void AddDocumentTypesForOrganization(ref Organization bdt)
        {

        }

        private void AddDocumentTypesForPatient(ref Patient bdt)
        {
            if(bdt.DocumentTypes != null)
                bdt.DocumentTypes.Clear();

        }

        private void SubmitValidation()
        {
            ErrorList = new List<string>();

            string organizationId = TextOrganizationSearchId.Text;
            if (organizationId.Length != 3)
            {
                ErrorList.Add("事業所名を選択してください");
                ErrorList.Add("事業所IDを入力してください");
            }

            if (CategoryA.IsChecked == false && CategoryB.IsChecked == false && CategoryC.IsChecked == false)
            {
                ErrorList.Add("書類タイプを選択してください");
            }

            bool hasSelected = false;

            /*
            foreach (BoolStringClass b in TagList)
            {
                if (b.Selected == true)
                {
                    hasSelected = true;
                    break;
                }
            }
             */

            if (hasSelected == false)
            {
                ErrorList.Add("書類名を選択してください");
            }


        }

        private void ButtonSearchClear_Click(object sender, RoutedEventArgs e)
        {
            CategoryA.IsChecked = false;
            CategoryB.IsChecked = false;
            CategoryC.IsChecked = false;

            //TextOrganizationSearchId.Text = "";
            ComboOrganizationSearchName.SelectedIndex = 0;
            TagList.Clear();
            TextPatientSearchId.Text = "";
            TextPatientSearchName.Text = "";
            ComboRetentionPeriodSearchUnit.SelectedIndex = 0;
            ComboRetentionPeriodSearchValue.SelectedIndex = 0;

            TreeViewDocumentTypeAC.Visibility = System.Windows.Visibility.Hidden;
            TreeViewDocumentTypeB.Visibility = System.Windows.Visibility.Hidden;
            BrowserPdfViewer.Source = null;
            //this.Close();
        }

        private void ButtonTagAdd_click(object sender, RoutedEventArgs e)
        {
            if (CustomTagList != null)
            {
                string newTag = TextNewTagName.Text;
                CustomTagList.Add(new Tag { Id = "Hard-Code-900", Name = newTag });
                ListViewDocumentCustomTag.Items.Refresh();
            }
        }


        private void TextPatientId_KeyUp(object sender, KeyEventArgs e)
        {
            if (TextPatientId.Text.Length >= 3)
            {
                string id = TextPatientId.Text.Substring(0, 3);
                Patient p = PatientList.Find(x => x.Id == id);

                SetPatientProperties(p);
            }
        }

        private void TextPatientSearchId_KeyUp(object sender, KeyEventArgs e)
        {
            if (TextPatientSearchId.Text.Length >= 3)
            {
                string id = TextPatientSearchId.Text.Substring(0, 3);
                Patient p = PatientList.Find(x => x.Id == id);

                if (p != null)
                {
                    TextPatientSearchId.Text = p.Id;
                    TextPatientSearchName.Text = p.Name;
                }
                else
                {
                    TextPatientSearchName.Text = "";
                }
            }
        }

        private void ComboPatientName_click(object sender, RoutedEventArgs e)
        {

            Patient p = (Patient)ComboPatientName.SelectedItem;
           
            SetPatientProperties(p);
            
        }

        private void TextPatientSearchName_KeyUp(object sender, KeyEventArgs e)
        {
            if (TextPatientSearchName.Text.Length >= 2)
            {
                string name = TextPatientSearchName.Text.Substring(0, 2);

                Patient p = PatientList.Find(x => x.Name == name);
                if (p != null)
                {
                    TextPatientSearchId.Text = p.Id;
                    TextPatientSearchName.Text = p.Name;
                }
                else
                {
                    TextPatientSearchId.Text = "";
                }
            }
            else
            {
                TextPatientSearchId.Text = "";
            }
        }


        private void SetPatientProperties(Patient p)
        {
            if (p != null)
            {
                TextPatientId.Text = p.Id;
                ComboPatientName.SelectedItem = p;
                LabelPatientAddress.Content = p.Address;
                LabelPatientDateOfBirth.Content = p.DataOfBirth;
                LabelPatientSex.Content = p.Sex;
            }
            else
            {
                TextPatientId.Text = "";
                ComboPatientName.SelectedIndex = 0;
                LabelPatientAddress.Content = "";
                LabelPatientDateOfBirth.Content = "";
                LabelPatientSex.Content = "";
            }
        }

        private void DocumentType_Change(object sender, RoutedEventArgs e)
        {

            DocumentType d = (DocumentType)ComboDocumentType.SelectedItem;

            if (d != null)
            {
                LoadDocumentNames(d.Id);

                if(d.Name.StartsWith("B"))
                    RowPatientInformation.Visibility = System.Windows.Visibility.Visible;
                else
                    RowPatientInformation.Visibility = System.Windows.Visibility.Hidden;
            }

        }

        private void DocumentName_Change(object sender, RoutedEventArgs e)
        {
            Document d = (Document)ComboDocumentName.SelectedItem;
            if (d != null)
            {
                LoadTags(d.Id);
            }
        }
       
        public void CreateCheckBoxList(int index)
        {
           
            switch (index)
            {
                case 0:
                    SearchPatientComponentView(System.Windows.Visibility.Hidden);
                    break;
                case 1:
                    SearchPatientComponentView(System.Windows.Visibility.Hidden);
                    break;
                case 2:
                    SearchPatientComponentView(System.Windows.Visibility.Visible);
                    break;
                case 3:
                    SearchPatientComponentView(System.Windows.Visibility.Hidden);
                    break;
            }

           
           TagList.Clear();
           
        }

        private void RetentionPeriodChange_click(object sender, RoutedEventArgs e)
        {
           
            if (ComboRetentionPeriodSearchValue != null && ComboRetentionPeriodSearchUnit != null &&
                DatePickerRangeEndDate != null && DatePickerRangeStartDate != null)
            {
                string RetentionPeriodValue = ComboRetentionPeriodSearchValue.SelectedItem.ToString();
                int RetentionPeriodUnit = ComboRetentionPeriodSearchUnit.SelectedIndex;

                int PeriodInteger = 5 - Convert.ToInt32(ComboRetentionPeriodSearchValue.SelectedIndex);
                DateTime dateTime = DatePickerRangeEndDate.SelectedDate.Value;

                if (RetentionPeriodUnit == 0)
                {
                    DatePickerRangeStartDate.SelectedDate = dateTime.AddYears(-PeriodInteger);
                }
                else if (RetentionPeriodUnit == 1)
                {
                    DatePickerRangeStartDate.SelectedDate = dateTime.AddMonths(-PeriodInteger);
                }
                else if (RetentionPeriodUnit == 2) 
                {
                    DatePickerRangeStartDate.SelectedDate = dateTime.AddDays(-(PeriodInteger * 7));
                } else
                {
                    DatePickerRangeStartDate.SelectedDate = dateTime.AddDays(-PeriodInteger);
                }
            }
        }

        private void ComboOrganizationSearchName_click(object sender, RoutedEventArgs e)
        {
            TextOrganizationSearchId.Text = ComboOrganizationSearchName.SelectedValue.ToString();
        }

        private void ComboOrganizationName_click(object sender, RoutedEventArgs e)
        {
            Organization org = (Organization)ComboOrganizationName.SelectedItem;
            if (org != null)
            {
                TextOrganizationId.Text = org.Code;

                NameValueCollection vals = new NameValueCollection();
                vals.Add("anyId", org.Id);
                string resourceUrl = "/search/search-organization-code-json";
                OrganizationPatientJSON orgs = JsonReader.JsonDeserialize<OrganizationPatientJSON>(SERVER_URL + resourceUrl, "POST", vals);

                PatientList = orgs.patients;
                ComboPatientName.ItemsSource = PatientList;

            }
        }

        private void TextOrganizationId_LostFocus(object sender, RoutedEventArgs e)
        {
            string code = TextOrganizationId.Text;
           
            if (this.Organizations != null)
            {
                foreach (Organization o in Organizations)
                {
                    if (o.Code.Equals(code))
                    {
                        ComboOrganizationName.SelectedValue = o.Code;
                        return;
                    }
                }
            }
            
            ComboOrganizationName.SelectedIndex = 0;
            TextOrganizationId.Text = INVALID_ID;

        }

        private void TextOrganizationSearchId_LostFocus(object sender, RoutedEventArgs e)
        {
            string id = TextOrganizationSearchId.Text;
            Organization org;

            org = Organizations.Find(x => x.Id == id);

            if (org != null)
            {
                ComboOrganizationSearchName.SelectedValue = org.Id;
                TextOrganizationSearchId.Text = org.Id;
            }
            else
            {
                ComboOrganizationSearchName.SelectedIndex = 0;
                TextOrganizationSearchId.Text = INVALID_ID;
            }
        }

        private void CheckBoxZone_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox chkZone = (CheckBox)sender;
        } 

        private void CategoryRadio_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton RadioCategory = (RadioButton)sender;
            switch (RadioCategory.Name)
            {
                case "CategoryA" :
                    CreateCheckBoxList(1);
                    break;
                case "CategoryB" :
                    CreateCheckBoxList(2);
                    break;
                case "CategoryC" :
                    CreateCheckBoxList(3);
                    break;
                default :
                    CreateCheckBoxList(0);
                    break;
            }
        }

        private void RadioRetentionPeriodYes_Clicked(object sender, RoutedEventArgs e)
        {
            ComboRetentionPeriodValue.SelectedIndex = 0;
            ComboRetentionPeriodUnit.SelectedIndex = 0;
            BooleanPropertySet(true, ComboRetentionPeriodUnit, ComboRetentionPeriodValue);
        }

        private void RadioRetentionPeriodNo_Clicked(object sender, RoutedEventArgs e)
        {
            ComboRetentionPeriodValue.Text = "";
            ComboRetentionPeriodUnit.Text = "";
            BooleanPropertySet(false, ComboRetentionPeriodUnit, ComboRetentionPeriodValue);
        }

        private void BooleanPropertySet(bool state, params UIElement[] elements)
        {
            foreach (UIElement arg in elements)
            {
                arg.IsEnabled = state;
            }
        }

        public void RadioPdfPageYes_Clicked(object sender, RoutedEventArgs e)
        {
            BooleanPropertySet(true, DatePickerPdfDate);
        }

        public void RadioPdfPageNo_Clicked(object sender, RoutedEventArgs e)
        {
            DatePickerPdfDate.Text = "";
            BooleanPropertySet(false, DatePickerPdfDate);
        }


        private void ListViewHits_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = sender as ListViewItem;
            if (item != null && item.IsSelected)
            {
                Patient p = item.DataContext as Patient;
                BrowserPdfViewer.Source = new Uri(new System.IO.FileInfo(p.DocumentPath).FullName);
            }
        }

        private void CheckboxPatientSearch_Checked(object sender, RoutedEventArgs e)
        {
            if (CheckboxPatientSearch.IsChecked == true)
            {
                TextPatientSearchId.IsEnabled = true;
                TextPatientSearchName.IsEnabled = true;
            }
            else
            {
                TextPatientSearchId.IsEnabled = false;
                TextPatientSearchName.IsEnabled = false;
            }
        }

        public Organization ActiveOrganization
        {
            set {
                org = value;
            }
            get
            {
                this.org = Organizations.Find(x => x.Id == TextOrganizationId.Text);
                return this.org;
            }
        }

        private void SearchPatientComponentView(System.Windows.Visibility state)
        {
            LabelSearchPatientEnable.Visibility = state;
            LabelSearchPatientId.Visibility = state;
            LabelSearchPatientName.Visibility = state;
            CheckboxPatientSearch.Visibility = state;
            TextPatientSearchId.Visibility = state;
            TextPatientSearchName.Visibility = state;
        }

        protected void PdfPreviewEvent(object sender, MouseButtonEventArgs e)
        {
            if (ListViewFile.SelectedValue != null)
            {
                string pdfFile = ListViewFile.SelectedValue.ToString();
                
                string pdfPath = ConfigurationManager.AppSettings["scansnap_folder"];
                new BrowserPreview(@pdfPath + "\\" + pdfFile).Show();
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
